/*
 * Checkbox.cpp
 *
 *  Created on: 11-01-2011
 *      Author: Przemek
 */

#include "gui/Checkbox.hpp"
#include "gui/UIManager.hpp"
#include "gui/ClipArea.hpp"
#include "utils/GLUtils.hpp"
using std::string;

const float Checkbox::BOX_SIDE_SIZE = 20.0f;

Checkbox::Checkbox(bool checked, const string& text) :
	checked(checked), label(new Label(text))
{
	add(label);
	label->addMouseListener(this);
	setOpaque(false);
}

bool Checkbox::isChecked() const
{
	return checked;
}

void Checkbox::draw(const ClipArea& clipArea)
{
	static const float VERTICAL_SPACE = 10;
	const Dimension textSize =
			UIManager::getInstance().getGUIFont().measureTextSize(label->getText());
	const Dimension fullSize = textSize + Dimension(BOX_SIDE_SIZE + VERTICAL_SPACE, 0.0f);

	const geometry::Rectangle normalisedBounds(Vector(0, 0), getSize());
	Vector controlStart = normalisedBounds.getLeftCornerForCenteredDimension(fullSize);
	label->setPosition(controlStart + Vector(BOX_SIDE_SIZE + VERTICAL_SPACE, 0.0f));
	label->setSize(textSize);

	Container::draw(clipArea);
	clipArea.setGLClipArea();

	controlStart += Vector(0.0f, (textSize.getHeight() - BOX_SIDE_SIZE) / 2.0f);
	UIManager::getInstance().getCheckboxBackground().setGLState();
	GLUtils::drawRectangle(controlStart, Dimension(BOX_SIDE_SIZE, BOX_SIDE_SIZE));

	if(checked)
	{
		static const float offset = 2;
		glBegin( GL_LINES);
		UIManager::getInstance().getCheckboxCheck().setGLState();
		glVertex2f(controlStart.getX() + offset, controlStart.getY() + offset);
		glVertex2f(controlStart.getX() + BOX_SIDE_SIZE - offset, controlStart.getY() + BOX_SIDE_SIZE
				- offset);
		glVertex2f(controlStart.getX() + offset, controlStart.getY() + BOX_SIDE_SIZE - offset);
		glVertex2f(controlStart.getX() + BOX_SIDE_SIZE - offset, controlStart.getY() + offset);
		glEnd();
	}
}

void Checkbox::mouseReleased(const MouseListener::EventArguments& arguments)
{
	checked = !checked;
	notifyMouseReleased(arguments);
}
